package org.dizem.groupon.action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.dizem.groupon.model.domain.UserEntity;
import org.dizem.groupon.service.UserService;

/**
 * User: dizem@126.com
 * Time: 11-6-23 上午10:26
 */
public class RegisterAction extends ActionSupport implements ModelDriven<UserEntity> {

	private UserService service;
	private UserEntity user;
	private String cityName;
	private String validation;

	public String getCityName() {
		return cityName;
	}

	public void setCityName(String cityName) {
		this.cityName = cityName;
	}

	public UserEntity getUser() {
		return user;
	}

	public void setUser(UserEntity user) {
		this.user = user;
	}

	public String getValidation() {
		return validation;
	}

	public void setValidation(String validation) {
		this.validation = validation;
	}

	public UserService getService() {
		return service;
	}

	public void setService(UserService service) {
		this.service = service;
	}

	@Override
	public void validate() {
		try {
			String code = (String) ActionContext.getContext().getSession().get("validation_code");
			if (!validation.equalsIgnoreCase(code)) {
				addFieldError("validation", "验证码错误");
				return;
			}
			if (service.isEmailExisted(user.getEmail())) {
				addFieldError("user.email", "该邮箱已被注册");
			}
			if (service.isUsernameExisted(user.getUsername())) {
				addFieldError("user.username", "该用户名已存在");
			}

		} finally {
			ActionContext.getContext().getSession().remove("validation_code");
		}
	}

	@Override
	public String execute() throws Exception {
		service.register(user, cityName);
		ActionContext.getContext().getSession().put("reg_username", user.getUsername());
		ActionContext.getContext().getSession().put("reg_email", user.getEmail());
		return SUCCESS;
	}

	public UserEntity getModel() {
		return user;
	}
}
